import { useEffect } from 'react';
import Cookies from 'js-cookie';
import useUserStore from './user';
import useResourcesStore from './resources';

export const useInitApp = () => {
    
  const { token, isLogin, login } = useUserStore();
  const { fetchResources } = useResourcesStore();

  useEffect(() => {
    // 应用启动时检查是否有保存的认证信息
    const savedToken = Cookies.get('auth');
    const savedUser = localStorage.getItem('user');
    if (savedToken && savedUser && !isLogin) {
      try {
        const userInfo = JSON.parse(savedUser);
        // 恢复用户状态
        login(savedToken, userInfo);
        // 获取菜单资源
        fetchResources();
      } catch (error) {
        console.error('恢复用户状态失败:', error);
        // 清除无效的认证信息
        Cookies.remove('auth', { path: '/' });
        localStorage.removeItem('auth');
        localStorage.removeItem('user');
      }
    }
  }, []); // 只在组件挂载时执行一次

  return { token, isLogin };
}; 